<?php

define('THIS_DIR', dirname(realpath(__FILE__)));
define('PROTOCOL', 'http');
define('HOST', 'local.com');
define('ROOT_PATH', '/my');
define('ROOT_URL', PROTOCOL . '://' . HOST . ROOT_PATH);
define('DS', '\\');


function generateFile($file_name, $file_id)
{
    $css_text = file_get_contents(THIS_DIR . '/css/' . $file_name . '.css');
    $tmp_file_name = THIS_DIR . '/_css/tmp_style.css';
    $tmp_css_file = fopen($tmp_file_name, 'w');
    fwrite($tmp_css_file,
    "<?php
    \$protocol  = '".PROTOCOL."';
    \$host      = '".HOST."';
    \$root_path = '".ROOT_PATH."';
    \$root      = '".ROOT_URL."';
    ?>\n" . $css_text);
    fclose($tmp_css_file);

    $css = array();
    ob_start();
    include($tmp_file_name);
    $css = ob_get_contents();
    ob_end_clean();
    unlink($tmp_file_name);

    $css_file = fopen(THIS_DIR . '/_css/' . $file_name . '.' . $file_id . '.css', 'w');
    fwrite($css_file, $css);
    fclose($css_file);
}

function getFileId($file_name)
{
    $files = scandir(THIS_DIR . '/_css/');
    $id = '';
    foreach ($files as $file) {
        if (preg_match('/^'.$file_name.'\.([^.]+)\.css$/', $file, $matches) && isset($matches[1])) {
            $id = $matches[1];
            break;
        }
    }
    return $id;
}

$file_name = isset($_GET['file']) ? $_GET['file'] : '';
$file_path = THIS_DIR . '/css/' . $file_name . '.css';
if (! strlen($file_name) || ! file_exists($file_path)) {
    die();
}

$file_id = md5(filemtime($file_path) . filesize($file_path) . ROOT_URL);

if ($curr_id = getFileId($file_name)) {
    if ($curr_id != $file_id) {
        unlink(THIS_DIR . '/_css/' . $file_name . '.' . $curr_id . '.css');
        generateFile($file_name, $file_id);
    }
} else {
    generateFile($file_name, $file_id);
}

header('Content-Type: text/css; charset="UTF-8"');
echo file_get_contents(THIS_DIR . '/_css/' . $file_name . '.' . $file_id . '.css');

?>
